from django.shortcuts import render
from django.views import View
from apps.verification.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django import http
import json, logging, re, random
from apps.verification.libs.yuntongxun.ccp_sms import CCP
from celery_tasks.sms.tasks import ccp_send_sms_code
from django.conf import settings

logger = logging.getLogger('django')


# Create your views here.
class ImageCodeView(View):
    """图形验证码
    GET http://www.meiduo.site:8000/image_codes/550e8400-e29b-41d4-a716-446655440000/
    """

    def get(self, request):
        cur = request.GET.get('cur')
        # print(cur)

        # 生成图形验证码
        text, image = captcha.generate_captcha()

        # 保存图形验证码
        # 使用配置的redis数据库的别名，创建连接到redis的对象
        redis_conn = get_redis_connection('verification')
        # 使用连接到redis的对象去操作数据存储到redis
        # redis_conn.set('key', 'value') # 因为没有有效期
        # redis_conn.setex('key', '过期时间', 'value')
        redis_conn.setex('img_%s' % cur, 300, text)

        # 响应图形验证码: image/jpg
        return http.HttpResponse(image, content_type='image/jpg')


class sendSMSCodeView(View):
    def post(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        mobile = json_dict.get('mobile')
        cur = json_dict.get('id')
        text = json_dict.get('text')

        # 校验参数
        if not all([mobile, cur, text]):
            return http.JsonResponse({'errno': 4002, 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return http.JsonResponse({'errno': 4004, 'errmsg': '参数mobile有误'})

        redis_conn = get_redis_connection('verification')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'errno':4201, 'errmsg': '频繁发送短信'})


        image_code_server = redis_conn.get('img_%s' % cur)
        if not image_code_server:

            return http.JsonResponse({'errno': 4002, 'errmsg': '图形验证码过期'})

        try:
            redis_conn.delete('img_%s' % cur)
        except Exception as e:
            logger.error(e)
        image_code_server=image_code_server.decode()
        if text.lower() != image_code_server.lower():
            return http.JsonResponse({'errno': 4004, 'errmsg': '输入图形验证码有误'})

        # 发送短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        logger.info(sms_code)
        print(sms_code)
        # 设置短信验证码有效期
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, 300, sms_code)
        pl.setex('send_flag_%s' % mobile, 60, 1)
        pl.execute()

        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        ccp_send_sms_code.delay(mobile, sms_code)

        return http.JsonResponse({'errno': 0, 'errmsg': '发送成功'})





